/*********************************************************************************
 *      Copyright:  (C) 2020 YangZhengQing<2489833081@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  receive_data.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(04/08/2020)
 *         Author:  YangZhengQing <2489833081@qq.com>
 *      ChangeLog:  1, Release initial version on "04/08/2020 04:25:19 PM"
 *                 
 ********************************************************************************/

#include "../include/server.h"

#define BUFFSIZE 100
/*功能：接收数据
 *参数：fd：传入文件描述符
        buff：传出接收到的数据
  返回值：成功返回接收的字节数，失败返回-1*/

char* receive_data(int fd)
{
    int                 rv = -1;
    char                *ptr = malloc(BUFFSIZE*sizeof(char));

    rv = read(fd, ptr, BUFFSIZE);
    
    if( rv < 0)
    {
        printf("server  read from client[%d] failure\n", fd);
        free(ptr);
        return NULL;
    }
    else if(rv == 0)
    {
        printf("Client[%d] is disconnected!\n",fd);
        free(ptr);
        return NULL;
    }

    printf("server read [%d] bytes from clienfd[%d]\n",rv,fd);
    
    return ptr;
}


/*功能：发送数据
 *参数：fd：传入文件描述符
 *      buff:传入需要发送的数据
 *返回值：成功返回0，失败返回-1*/
int send_data(int fd,char *buff)
{
    int                     rv = -1;

    rv = write(fd,buff,strlen(buff));
    if(rv < 0)
    {
        printf("Writing response information to client[%d] is failed:%s\n",fd,strerror(errno));
        return -1;
    }

    return 0;
}

ssize_t readn(int fd, void *vptr, size_t n)
{
    size_t nleft;
    ssize_t nread;
    char *ptr;

    ptr = vptr;
    nleft = n;

    while (nleft > 0) {
        if ( (nread = read(fd, ptr, nleft)) < 0) {
            if (errno == EINTR)
                nread = 0;  /*  and call read() again */
            else
                return(-1);
        } else if (nread == 0)

            break;    /*  EOF */

        nleft -= nread;
        ptr += nread;
    }

    return(n - nleft);  /*  return >= 0 */

}
